/**
 * @Author: zc
 * @Date: 2019-11-16 11:55:17
 * @LastEditors: zc
 * @LastEditTime: 2020-08-27 16:51:27
*/

/* config-overrides.js */
const {
  override,
  addWebpackAlias,
  addWebpackPlugin,
  setWebpackPublicPath,
  fixBabelImports,
  addLessLoader
} = require("customize-cra")
const getGitCommit = require("./bash/getGitCommit");
const path = require('path')
const MockjsWebpackPlugin = require('mockjs-webpack-plugin')
const WebpackScpUploadPlugin = require('webpack-easy-upload-plugin')
require('react-app-rewire-less')

const {
  NODE_ENV,
  npm_package_name,
  REACT_APP_ISM,
  REACT_APP_PUBLIC_URL,
  REACT_APP_PRE_PUBLIC_URL,
  REACT_APP_MOCKPORT,
  REACT_APP_PASSWORD,
  REACT_APP_Width,
  REACT_APP_Height,
  REACT_APP_BUILD,
  OSS_BUCKET,
  REACT_APP_APITYPE,
  REACT_APP_CDN,
} = process.env
const isProduction = NODE_ENV === 'production'
const url = `/${npm_package_name}`
let _GIT_COMMIT_ID = getGitCommit();
const baseUrl = (REACT_APP_APITYPE === 'dynamic' || REACT_APP_CDN === 'true') ?  `${REACT_APP_PUBLIC_URL}/${OSS_BUCKET}/${npm_package_name}/${_GIT_COMMIT_ID}` : `${REACT_APP_PRE_PUBLIC_URL}${url}/${REACT_APP_BUILD}/`
const HOSTURL = isProduction ? baseUrl : '/'
process.env.PUBLIC_URL = HOSTURL

// 关闭sourceMap
process.env.GENERATE_SOURCEMAP = 'false'
const reSetAddWebpackPlugin = () => {
  if (isProduction) {
  return new WebpackScpUploadPlugin({
    username: 'root',
    host: '11.50.49.179',
    password: REACT_APP_PASSWORD,
    local: 'build',
    path: `/home/react${url}/${REACT_APP_BUILD}`
  })
  } else {
    return new MockjsWebpackPlugin({
      path: path.join(__dirname, './mocks'),
      port: Number(REACT_APP_MOCKPORT)
    })
  }
}

const dropConsole = () => {
  if (!isProduction) return
  return (config) => {
    if(config.optimization.minimizer){
      config.optimization.minimizer.forEach( (minimizer) => {
        if( minimizer.constructor.name === 'TerserPlugin'){
          minimizer.options.terserOptions.compress.drop_console = true
        }
      })
    }
    return config
  }
}


const addCustomize = () => config => {
  REACT_APP_ISM === 'true' ?
  require('react-app-rewire-postcss')(config, {
    plugins: loader => [
      require('postcss-flexbugs-fixes'),
      require('postcss-preset-env')({
        autoprefixer: {},
        stage: 3,
      }),
      require('postcss-aspect-ratio-mini')({}),
      require('postcss-px-to-viewport')({
        viewportWidth: Number(REACT_APP_Width), // (Number) The width of the viewport.
        viewportHeight: Number(REACT_APP_Height), // (Number) The height of the viewport.
        unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to.
        viewportUnit: 'vw', // (String) Expected units.
        selectorBlackList: ['.ignore', '.hairlines', '.jdfont'], // (Array) The selectors to ignore and leave as px.
        minPixelValue: 2, // (Number) Set the minimum pixel value to replace.
        mediaQuery: false, // (Boolean) Allow px to be converted in media queries.
        exclude: /(\/|\\)(pc)(\/|\\)/
      }),
      require('postcss-write-svg')({
        utf8: false
      }),
      require('postcss-viewport-units')({
        filterRule: rule => rule.nodes.findIndex(i => i.prop === 'content') === -1 && rule.selector.includes('::after') && rule.selector.includes('::before') && rule.selector.includes(':after') && rule.selector.includes(':before')
      }),
      require('cssnano')({
        "cssnano-preset-advanced": {
          "zindex": false,
          "autoprefixer": false
        }
      })
    ]
  }) :
  require('autoprefixer')({})
  return config;
}

module.exports = {
  webpack: override(
    // disableEsLint(),
    addWebpackAlias({
      '@': path.resolve(__dirname, './src')
    }),
    setWebpackPublicPath(HOSTURL),
    // 插件
    addWebpackPlugin(
      reSetAddWebpackPlugin()
    ),
    dropConsole(),
    fixBabelImports('import', {
      libraryName: 'antd-mobile',
      style: true,
    }),
    addLessLoader({
      javascriptEnabled: true // 支持less的js语法功能
      // modifyVars: { '@primary-color': '#1DA57A' }, # 这里不注释掉，那你的无法修改主题色primary-color 这里很坑的 要注意！
    }),
    addCustomize()
  )
}